package com.guli.order.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guli.common.pojo.vo.StatusCodeEnum;
import com.guli.mall.serviceBase.globalException.MallException;
import com.guli.order.vo.AliPayAsyncCallBackVo;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.guli.common.utils.Query;

import com.guli.order.mapper.PaymentInfoMapper;
import com.guli.order.entity.PaymentInfoEntity;
import com.guli.order.service.PaymentInfoService;


@Service("paymentInfoService")
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfoEntity> implements PaymentInfoService {

    public static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Page<PaymentInfoEntity> queryPage(Integer currentPage, Integer size, Map<String, Object> params) {

        Page<PaymentInfoEntity> page = new Page<>(currentPage, size);

        return this.page(page);
    }

    @Override
    public void saveToPaymentInfo(AliPayAsyncCallBackVo aliPayAsyncCallBackVo) throws ParseException {
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();

        paymentInfoEntity.setOrderSn(aliPayAsyncCallBackVo.getOut_trade_no());

        paymentInfoEntity.setAlipayTradeNo(aliPayAsyncCallBackVo.getTrade_no());

        paymentInfoEntity.setCreateTime(aliPayAsyncCallBackVo.getGmt_create());

        paymentInfoEntity.setConfirmTime(aliPayAsyncCallBackVo.getGmt_payment());

        paymentInfoEntity.setCallbackContent(aliPayAsyncCallBackVo.getPassback_params());

        paymentInfoEntity.setSubject(aliPayAsyncCallBackVo.getSubject());

        paymentInfoEntity.setTotalAmount(aliPayAsyncCallBackVo.getReceipt_amount());

        paymentInfoEntity.setPaymentStatus(aliPayAsyncCallBackVo.getTrade_status());
        /**
         * 状态 TRADE_SUCCESS 的通知触发条件是商户签约的产品支持退款功能的前提下，买家付款成功；
         *
         * 交易状态 TRADE_FINISHED 的通知触发条件是商户签约的产品不支持退款功能的前提下，买家付款成功；或者，商户签约的产品支持退款功能的前提下，交易已经成功并且已经超过可退款期限。
         * */
        if(aliPayAsyncCallBackVo.getTrade_status().equals("TRADE_SUCCESS")||aliPayAsyncCallBackVo.getTrade_status().equals("TRADE_FINISHED")){

            this.save(paymentInfoEntity);
        }else{
            throw new MallException(StatusCodeEnum.ALI_PAY_PAYMENT_FAILED);
        }
    }

}